<template>
  <div class="app-container question-bank">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="题目内容" prop="topicContent">
        <el-input
          v-model="queryParams.topicContent"
          placeholder="请输入题目内容"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
          @clear="resetQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="queryParams.type">
          <el-radio value="">全部</el-radio>
          <el-radio :value="0">单选</el-radio>
          <el-radio :value="1">多选</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['questionBank:import']"
          >导入</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="tableList" border>
      <el-table-column label="序号" type="index" align="center" width="70" />
      <el-table-column label="类型" prop="type" align="center" width="80">
        <template #default="scope">
          <el-tag type="primary" v-if="scope.row.type == 1">多选</el-tag>
          <el-tag type="warning" v-if="scope.row.type == 0">单选</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="题目内容"
        prop="topicContent"
        show-overflow-tooltip
        min-width="50px"
        align="left"
      />
      <el-table-column
        label="选项内容"
        prop="optionContent"
        align="left"
        min-width="50px"
      >
        <template #default="scope">
          <template v-if="scope.row.optionContent.length">
            <el-tooltip placement="left" effect="dark">
              <template #content>
                <p
                  v-for="(item, index) in scope.row.optionContent"
                  :key="index"
                >
                  {{ item.option }}： {{ item.optionCount }}
                </p>
              </template>
              <div class="option-content">
                <template
                  v-for="(item, index) in scope.row.optionContent"
                  :key="index"
                >
                  {{ item.option }}： {{ item.optionCount }}<br />
                </template>
              </div>
            </el-tooltip>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        label="正确答案"
        prop="correctAnswer"
        align="center"
        width="100"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="150"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            text
            @click="handleDeatil(scope.row)"
            v-hasPermi="['questionBank:detail']"
          >
            详情
          </el-button>

          <el-button
            link
            type="primary"
            text
            @click="handleDelete(scope.row)"
            v-hasPermi="['questionBank:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      align-center
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center mt10">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="downloadTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog
      title="题目详情"
      v-model="open"
      width="35vw"
      align-center
      append-to-body
    >
      <el-form :model="form" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="题目内容：">{{
              form.topicContent
            }}</el-form-item>
            <el-form-item label="类型：">
              <el-tag type="primary" v-if="form.type == 1">多选</el-tag>
              <el-tag type="warning" v-if="form.type == 0">单选</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选项内容：">
              <div
                class="detail-options-content"
                v-if="form.optionContent.length"
              >
                <p
                  v-for="(item, index) in form.optionContent"
                  :key="index"
                  style="line-height: 10px"
                >
                  {{ item.option }}： {{ item.optionCount }}
                </p>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="正确答案：">{{
              form.correctAnswer
            }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="StudyQuestionBank">
import { getToken } from "@/utils/auth";

import {
  listQuestionBank,
  getQuestionBankById,
  delQuestionBank,
} from "@/api/other/questionBank";

const { proxy } = getCurrentInstance();

const tableList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/question-bank/importData",
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    topicContent: undefined,
    type: "",
  },
});

const { queryParams, form } = toRefs(data);

/** 查询题库列表 */
function getList() {
  loading.value = true;
  listQuestionBank(queryParams.value).then((response) => {
    const { data } = response;
    tableList.value = data.records ?? [];
    if (tableList.value.length) {
      tableList.value = data.records.map((item) => {
        if (item.optionContent) {
          item.optionContent = JSON.parse(item.optionContent);
        } else {
          item.optionContent = [];
        }
        return item;
      });
    }
    total.value = data.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 详情按钮操作 */
function handleDeatil(row) {
  getQuestionBankById({ id: row.id }).then((response) => {
    form.value = response.data;
    if (form.value.optionContent) {
      form.value.optionContent = JSON.parse(form.value.optionContent);
    } else {
      form.value.optionContent = [];
    }
    open.value = true;
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm("确认删除该数据？", "删除确认")
    .then(function () {
      return delQuestionBank(row.id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 关闭按钮操作 */
function close() {
  open.value = false;
  form.value = {};
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "题库导入";
  upload.open = true;
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

/** 下载模板 */
function downloadTemplate() {
  let a = document.createElement("a");
  fetch("https://mscy.cqlandun.com:8088/static/question-template.xlsx")
    .then((res) => res.blob())
    .then((blob) => {
      a.href = URL.createObjectURL(blob);
      a.download = "社区警务题库导入模板";
      a.style.display = "none";
      a.click();
      window.URL.revokeObjectURL(a.href);
    });
}

getList();
</script>

<style lang="scss" scoped>
.question-bank {
  :deep(.el-table .cell.el-tooltip) {
    white-space: wrap;
    overflow: hidden;
    -webkit-line-clamp: 4;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
  }
  .option-content {
    overflow: hidden;
    -webkit-line-clamp: 4;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
  }
}
</style>
